<template>
    <div class="app-container">
       <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="82px">
        <!-- <el-form-item label="摄像" prop="cameraIndexCode">
            <el-input v-model="queryParams.cameraIndexCode" placeholder="请输入摄像头编码" clearable style="width: 240px"
               @keyup.enter="handleQuery" />
         </el-form-item> -->
         <el-form-item label="摄像头名称" prop="resName">
            <el-input v-model="queryParams.resName" placeholder="请输入摄像头名称" clearable style="width: 240px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="区域名称" prop="areaId">
             <el-select v-model="queryParams.areaId" placeholder="请选择区域名称" style="width: 240px"
                @keyup.enter="handleQuery">
                <el-option v-for="item in areaOptions" :key="item.areaId" :label="item.name" :value="item.areaCode" />
             </el-select>
          </el-form-item>
          <el-form-item label="事件等级" prop="eventLevel">
             <el-select v-model="queryParams.eventLevel" placeholder="请选择事件等级" style="width: 240px"
                @keyup.enter="handleQuery">
                <el-option v-for="item in sys_event_level" :key="item.value" :label="item.label" :value="item.value" />
             </el-select>
          </el-form-item>
          <!-- <el-form-item label="预警方式" prop="warningWay">
             <el-select v-model="queryParams.warningWay" placeholder="请选择预警方式" style="width: 240px"
                @keyup.enter="handleQuery">
                <el-option v-for="item in warningWaysOptions" :key="item.id" :label="item.name" :value="item.id" />
             </el-select>
          </el-form-item> -->
          <el-form-item label="开始时间" style="width: 308px">
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
               start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
         </el-form-item>
          <el-form-item>
             <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
             <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
       </el-form>
       <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
             <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['contact:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
             <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                v-hasPermi="['contact:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
             <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['contact:remove']">删除</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getRefreshPage"></right-toolbar>
       </el-row>
       <!-- 表格数据 -->
       <el-table v-loading="loading" :data="roleList" >
         <el-table-column label="摄像头名称" align="center" prop="resName" :show-overflow-tooltip="true" />
         <el-table-column label="事件类型" align="center" prop="warningType" :show-overflow-tooltip="true" >
            <template #default="scope">
               <!-- {{ sys_warning_type.find(item => item.value == scope.row.warningType)?.label }} -->
               {{ sys_warning_type[0].label}}
            </template>
         </el-table-column>
         <el-table-column label="时间" align="center" prop="warningTime" width="150">
             <template #default="scope">
                <span>{{ parseTime(scope.row.warningTime) }}</span>
             </template>
          </el-table-column>
          <el-table-column label="所在区域" align="center" prop="regionIndexCode" width="150">
             <template #default="scope">
               {{ areaOptions.find(e=>e.areaCode==scope.row.regionIndexCode)?.name }}
             </template>
          </el-table-column>
          <el-table-column label="事件源" align="center" prop="resName" :show-overflow-tooltip="true" />
          <el-table-column label="事件等级" width="100" align="center" prop="eventLevel" :show-overflow-tooltip="true">
            <template #default="scope">
               {{ sys_event_level.find(item => item.value == scope.row.eventLevel)?.label }}
            </template>
         </el-table-column>
          <el-table-column label="报警温度温度" align="center" prop="curTemperature" :show-overflow-tooltip="true" />
         <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="查看" align="center" class-name="small-padding fixed-width" width="240">
            <template #default="scope">
                  <el-button link type="primary"  @click="openImage(scope.row)"
                     >图片</el-button>
                  <el-button link type="primary"  @click="openVideo(scope.row)"
                     >视频</el-button>
            </template>
         </el-table-column>
       </el-table>
       <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
        
      <el-image-viewer v-if="isViewerVisible" :url-list="imageUrls" @close="closeImageViewer" />
      <el-dialog  destroy-on-close v-model="dialogVisible" :show-close="false"  style="padding: 0 !important;background-color: transparent; " id="videoDialog"  width="60%" @close="dialogClose"  append-to-body>
            <div class="player-container">
            <div class="colse-button" @click="dialogVisible = false">
               <el-icon size="24"><Close /></el-icon>
            </div>
            <video id="my-video" ref="myVideo" style="width: 100%;height: 100%;" class="video-js vjs-big-play-centered"    controls preload="auto" >
               <source  >
            </video>
            <div v-if="showProgress" class="progress-container">
               <div class="progress-bar" :style="{ width: progress + '%' }"></div>
               <div style="color: #fff;text-align: center; margin-top: 5px;" >
                  正在加载请稍等..
               </div>
            </div>
            </div>
      </el-dialog>
    </div>
 </template>
 
 <script setup name="event">
 import { pageEvent,pictureUrl,getVideo,refreshEvent} from "@/api/alarm/event";
 import videojs from 'video.js';
 import 'video.js/dist/video-js.css'
 import {pageArea} from '@/api/area.js'
import { getToken } from '@/utils/auth'
import { onMounted,nextTick}from 'vue'
 const router = useRouter();
 const { proxy } = getCurrentInstance();
 const { sys_warning_type,sys_event_level } = proxy.useDict("sys_warning_type","sys_event_level");
 const options = ref([])
 const roleList = ref([]);
 const dialogVisible = ref(false);
 const loading = ref(true);
 const showSearch = ref(true);
 const total = ref(0);
 const dateRange = ref([]);
 const deptOptions = ref(undefined);
 const data = reactive({
    form: {},
    queryParams: {
       pageNum: 1,
       pageSize: 10,
       roleName: undefined,
       roleKey: undefined,
       status: undefined
    },
 });


function getRefreshPage() {
    loading.value = true;
    if (dateRange.value && dateRange.value.length > 0) {
       queryParams.value.createTimeStart = dateRange.value[0]
       queryParams.value.createTimeEnd = dateRange.value[1]
    } else {
       queryParams.value.createTimeStart = undefined
       queryParams.value.createTimeEnd = undefined
    }
    refreshEvent(proxy.addDateRange(queryParams.value)).then(response => {
       roleList.value = response?.data?.rows;
       total.value = response?.data?.total;
       loading.value = false;
    });
 }

 const { queryParams, form, rules } = toRefs(data);
 function getList() {
    loading.value = true;
    if (dateRange.value && dateRange.value.length > 0) {
       queryParams.value.startTime = dateRange.value[0]
       queryParams.value.endTime = dateRange.value[1]
    } else {
       queryParams.value.startTime = undefined
       queryParams.value.endTime = undefined
    }
    pageEvent(proxy.addDateRange(queryParams.value)).then(response => {
       roleList.value = response?.data?.rows;
       total.value = response?.data?.total;
       loading.value = false;
    });
 }
const poster = ref('')
//预览图片
const isViewerVisible = ref(false)
const imageUrls = ref();

const openImage =async (row)=>{
   const res = await pictureUrl(row.id)
   imageUrls.value = [res.data]
   isViewerVisible.value = true
}

const closeImageViewer = ()=>{
   isViewerVisible.value = false
}


let player = ref()
const progress = ref(0)
let timer;
const startProgressTimer = () => {
  timer = setInterval(() => {
    if (progress.value < 98) {
      progress.value += 0.02;
    } else {
      clearInterval(timer);
    }
  }, 9);
};
// 控制进度条是否显示
let blobUrl = ref()
const showProgress = ref(false);
const initVideo = (id) => {
   nextTick(async ()=>{
      //启动进度条
      blobUrl.value = null
      progress.value = 0
      showProgress.value = true;
      startProgressTimer();
      const response = await fetch(`${import.meta.env.VITE_APP_BASE_API}/event/video?id=${id}`, {
          headers: {
            'Authorization': `Bearer ${getToken()}`,
          }
        });
        const blob = await response.blob();
        blobUrl.value = URL.createObjectURL(blob);
        progress.value = 100
         clearInterval(timer);
         showProgress.value = false;
      player.value = videojs('my-video',{
         controls: true,
         autoplay: true,
         preload: 'auto',
         sources: [{
            src: blobUrl.value,
            type: 'video/mp4'
          }]
      });
      // 监听 loadstart 事件，开始显示进度条
      player.value.on('loadstart', () => {
         // console.log('显示进度条');
         // showProgress.value = true;
         // startProgressTimer();
      });
      // 监听 canplay 事件，隐藏进度条
      player.value.on('canplay', () => {
         console.log('视频可以播放');
        
      });
      player.value.on('error', (error) => {
         console.log('视频加载过程中出现错误:', error);
         clearInterval(timer);
         showProgress.value = false;
      });
      })
      
};
const openVideo =  (row)=>{
   dialogVisible.value = true
   initVideo(row.id);
   // videoSrc.value  = `${import.meta.env.VITE_APP_BASE_API}/event/video?id=${row.id}`
}
const dialogClose = ()=>{
   URL.revokeObjectURL(blobUrl.value);
   clearInterval(timer)
   if (player.value) {
      player.value.dispose();
      player.value = null;
  }
}
const areaOptions = ref([])

 /** 查询部门下拉树结构 && 查询单位下拉选择 */
 function getDeptTree() {
   pageArea().then(response=>{
      areaOptions.value = response.data.rows
   })
 };
const cancel = ()=>{
   dialogVisible.value = false

}
const onPlay = () => console.log('播放')
const onPause = () => console.log('暂停')
 /** 搜索按钮操作 */
 function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
 }
 
 /** 重置按钮操作 */
 function resetQuery() {
    dateRange.value = [];
    queryParams.value.startTime = undefined
    queryParams.value.endTime = undefined
    proxy.resetForm("queryRef");
    handleQuery();
 }
 getDeptTree();

 getList();

 </script>
 <style scoped lang="scss">
 
 .progress-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 70%;
  height: 10px;
  background-color: #ccc;
  border-radius: 5px;
  z-index: 10;
}

.progress-bar {
  height: 100%;
  background-color: #007bff;
  border-radius: 5px;
}

 .player-container {
  width: 100%;
  height:600px;
  margin: 0 auto;
  position: relative;
  margin-top: 100px;
  /* 隐藏默认播放图标 */
  .colse-button{
   cursor: pointer;
   font-size: 18px;
   color: aliceblue;
   position: absolute;
   width: 44px;
   height: 44px;
   border-radius: 50%;
   display: flex;
   align-items: center;
   justify-content: center;
   background-color: #606266;
   right: -200px;
   top: -50px;
  }
}
 </style>
 <style lang="scss">
 .video-js .vjs-big-play-button {
      display: none ;
    }
#videoDialog{
      .el-dialog__header{
      padding-bottom: 0 !important;
      }
   }
</style>